<template>
  <div>
    <div class="content-section" v-loading="loading">
      <el-card style="height: 730px">
        <template #header>
          <div class="card-header">
            <span>我的钱包</span>
            <div>
              <el-button type="primary" link @click="Withdrawal"
                >提现记录</el-button
              >
              <el-button type="primary" link @click="FlowingWater"
                >资金流水</el-button
              >
              <el-button type="primary" link @click="Rechargerecord"
                >充值记录</el-button
              >
            </div>
          </div>
        </template>

        <div class="wallet-balance">
          <div class="wallet-balance-card">
            <div class="wallet-balance-img">
              <div class="balance-info">
                <span class="balance-text">账户余额</span>
                <span class="balance-amount"
                  >{{ balance.moneyAvailable }}元</span
                >
              </div>
              <div class="balance-detail">
                <div>
                  <span class="detail-label">可提现 </span>
                  <span class="detail-amount"
                    >{{ balance.moneyAvailable }}.00元</span
                  >
                </div>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <div>
                  <span class="detail-label">待结算 </span>
                  <span class="detail-amount"
                    >{{ balance.moneyInTransit }}元</span
                  >
                </div>
              </div>
            </div>
            <div class="wallet-balance-btn">
              <el-button type="primary" size="large" @click="withdraw"
                >提现</el-button
              >

              <el-popover placement="left" :width="960" trigger="click">
                <template #reference>
                  <el-button link>提现规则</el-button>
                </template>

                <!-- 自定义内容 -->
                <template #default>
                  <div class="withdraw-rules">
                    <h4 class="title">星网数据提现规则</h4>
                    <div class="content">
                      <h2>提现须知</h2>
                      <p>尊敬的创作者：</p>
                      <p>
                        感谢您选择 星网数据
                        平台进行知识分享！为持续为您提供优质的技术支持、流量推广及内容分发服务，平台将按以下规则收取服务费：
                      </p>
                      <p>
                        提现金额 = 可提现余额 ×80%（平台统一收取 20%
                        作为内容运营服务费）
                      </p>
                      <p>提现规则说明：</p>
                      <div style="margin-left: 20px">
                        <p>1.微信支付订单财务结算周期15-20个工作日</p>
                        <p>
                          2.由于财务结算需要，有待结算金额，用户仅能提现已结算金额
                        </p>
                        <p>3.企业用户提现联系客服，公对公打款及开发票</p>
                        <p>
                          4.提现手续费：由第三方支付平台收取（约 0.1%-0.3%）
                        </p>
                        <p>5.最低提现金额10元，整数金额提取</p>
                        <p>
                          6.用户通过平台提现时，平台有权根据国家税收法规代扣税费
                        </p>
                      </div>
                      特别提醒：
                      平台收益数据每日更新，提现前请确认最新可提现金额
                    </div>

                    <div class="content">
                      <h2>提现流程</h2>
                      <p>点击“提现” → 确认提现金额 → 提交提现申请</p>
                      <p>
                        我们致力于为创作者打造公平透明的收益体系，如有任何疑问，欢迎随时联系客服（服务时间：9:00-18:00）。让我们共同成长，分享知识价值！
                      </p>
                    </div>
                  </div>
                </template>
              </el-popover>
            </div>
          </div>
        </div>

        <el-table :data="orders" style="width: 100%" border height="298px">
          <el-table-column prop="title" label="报告名称" min-width="200px">
            <template #default="{ row }">
              <el-tooltip :content="row.title" placement="top" effect="dark">
                <span class="name-link" @click="handleNameClick(row)">
                  {{ row.title }}
                </span>
              </el-tooltip>
            </template>
          </el-table-column>

          <el-table-column prop="payTime" label="支付日期">
            <template #default="{ row }">
              {{ formatTime(row.payTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="out_no" label="订单号" />
          <el-table-column prop="payMoney" label="结算金额" min-width="50px">
            <template #default="{ row }"> ￥ {{ row.payMoney }}</template>
          </el-table-column>
          <el-table-column prop="authorPayTime" label="预计结算时间">
            <template #default="{ row }">
              {{ formatTime(row.authorPayTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="authorPayRealTime" label="实际结算时间">
            <template #default="{ row }">
              {{
                Number(row.authorPayRealTime) > 0
                  ? formatTime(row.authorPayRealTime)
                  : "----"
              }}
            </template>
          </el-table-column>

          <el-table-column label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.authorPayStatus)" size="small">
                {{ getStatusText(row.authorPayStatus) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="Number(props.total)"
          :page="currentPage"
          :limit="pageSize"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </el-card>

      <!-- 提现弹窗 -->
      <el-dialog v-model="dialogFormVisible" title="账户提现" width="500px">
        <el-form :model="form" label-width="120px">
          <el-form-item label="到账账户">
            <div style="display: flex; align-items: center">
              <el-text>微信零钱 </el-text>
              <el-text
                style="font-size: 12px; color: #41bb83; margin-left: 10px"
              >
                (扫码登录的微信账号)</el-text
              >
            </div>
          </el-form-item>
          <el-form-item label="提现金额" style="width: 220px">
            <div style="display: flex; align-items: center">
              <el-input v-model="form.amount" placeholder="" />
              <span>元</span>
            </div>
          </el-form-item>

          <template v-if="personMsg">
            <el-form-item label="账户实名">
              <el-input
                v-model="form.realName"
                placeholder="请输入真实姓名"
                :disabled="personMsg"
                style="width: 250px"
              />
              <el-button
                type="text"
                icon="el-icon-plus"
                @click="addNewPerson"
                style="margin-left: 8px"
                v-if="form.length == 0"
                >添加姓名
              </el-button>
            </el-form-item>

            <el-form-item label="身份证号">
              <el-input
                v-model="form.cardNo"
                placeholder="请输入本人身份证号"
                :disabled="personMsg"
              />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input
                v-model="form.email"
                placeholder="请输入邮箱"
                :disabled="personMsg"
              />
            </el-form-item>

            <!-- 认证后修改提示 -->
            <div class="modify-tip" style="margin: 20px 0; text-align: center">
              如需修改已认证信息，请前往【 用户认证】提交修改
            </div>
          </template>

          <template v-else>
            <div class="modify-tip" style="margin: 20px 0; text-align: center">
              请先到【用户认证】完成实名认证后再提现
            </div>
          </template>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="ConfirmWithdrawal"
              >下一步</el-button
            >
          </div>
        </template>
      </el-dialog>

      <!-- 提现记录弹窗 -->
      <el-dialog v-model="dialogTableVisible" title="提现记录" width="1100">
        <el-table :data="gridData" border style="width: 100%" height="285px">
          <el-table-column prop="addTime" label="日期">
            <template #default="{ row }">
              {{ formatTime(row.addTime) }}
            </template>
          </el-table-column>

          <el-table-column prop="money" label="金额" width="180">
            <template #default="{ row }"> ￥ {{ row.money }} </template>
          </el-table-column>

          <el-table-column prop="name" label="到账账户" width="180" />

          <el-table-column prop="checkStatus" label="状态" width="180">
            <template #default="{ row }">
              <el-tag
                :type="getWithdrawStatusType(row.checkStatus)"
                size="small"
              >
                {{ getWithdrawStatusText(row.checkStatus) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 修改操作列 -->
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button
                style="color: #ecb86b"
                v-if="Number(row.checkStatus) === 2"
                @click="handleReceive(row)"
              >
                立即收款
              </el-button>
              <el-button v-else style="color: #98d679" @click="showDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <reportPagination
          :total="Number(walletQuery.total)"
          @current-change="handleCurrentChangewallet"
          @size-change="handleSizeChangewallet"
          :page="walletQuery.pageNum"
          :limit="walletQuery.pageSize"
        />
      </el-dialog>

      <!-- 二维码弹窗 -->
      <el-dialog v-model="dialogCodeVisible" title="二维码" width="500px">
        <div class="qrcode-container">
          <div class="qrcode-text">
            请使用系统登录的微信扫描二维码，既可收款
          </div>
          <div class="qrcode-image-wrapper">
            <img :src="imgcode" alt="微信收款二维码" />
          </div>
          <div class="qrcode-hint">
            提示：请确保使用登录本系统的微信账号扫码
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogCodeVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogCodeVisible = false"
              >确认</el-button
            >
          </div>
        </template>
      </el-dialog>

      <!-- 资金流水弹窗 -->
      <el-dialog v-model="FlowingWaterVisible" title="资金流水" width="1100">
        <el-table
          :data="FlowingWaterData"
          border
          style="width: 100%"
          height="240px"
        >
          <el-table-column prop="addTime" label="日期"> </el-table-column>
          <!-- <el-table-column prop="typName" label="类型" /> -->
          <el-table-column prop="name" label="操作名称" />

          <el-table-column prop="accPre" label="原有金额">
            <template #default="{ row }"> ￥ {{ row.accPre }} </template>
          </el-table-column>
          <el-table-column prop="currentNum" label="操作金额">
            <template #default="{ row }"> ￥ {{ row.currentNum }} </template>
          </el-table-column>
          <el-table-column prop="accNow" label="操作后金额">
            <template #default="{ row }"> ￥ {{ row.accNow }} </template>
          </el-table-column>
        </el-table>
        <reportPagination
          :total="Number(FlowingWaterParams.total)"
          @current-change="handleCurrentChangeFlowingWater"
          @size-change="handleSizeChangFlowingWater"
          :page="FlowingWaterParams.pageNum"
          :limit="FlowingWaterParams.pageSize"
        />
      </el-dialog>

      <!-- 充值记录弹窗 -->
      <el-dialog v-model="dialogRechargeVisible" title="充值记录" width="1100">
        <el-table
          :data="RechargeData"
          border
          style="width: 100%"
          height="285px"
        >
          <el-table-column prop="addTime" label="日期">
            <template #default="{ row }">
              {{ formatTime(row.addTime) }}
            </template>
          </el-table-column>

          <el-table-column label="金额">
            <template #default="{ row }"> ￥ {{ row.paymoney }} </template>
          </el-table-column>

          <!-- 修改支付方式列 -->
          <el-table-column prop="payType" label="支付方式">
            <template #default="{ row }">
              {{ row.payType === "wxpay" ? "微信支付" : row.payType }}
            </template>
          </el-table-column>

          <!-- 修改状态列 -->
          <el-table-column label="状态">
            <template #default="{ row }">
              <el-tag :type="getRechargeStatusType(row.payStatus)" size="small">
                {{ getRechargeStatusText(row.payStatus) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button style="color: #ecb86b" @click="showDetail(row)">
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <reportPagination
          :total="Number(rechargeTotal)"
          @current-change="handleCurrentChangeRecharge"
          @size-change="handleSizeChangeRecharge"
          :page="rechargeQuery.pageNum"
          :limit="rechargeQuery.pageSize"
        />
      </el-dialog>
      <!-- 充值记录二维码弹窗 -->
      <el-dialog v-model="RechargeVisible" title="二维码" width="500px">
        <div class="qrcode-container">
          <div class="qrcode-text">
         <span> {{RechargeTxt}}</span>
          </div>
          <div class="qrcode-image-wrapper">
            <img :src="Rechargeimgcode" alt="" />
          </div>
          <div class="qrcode-hint">
            <!-- 提示：请确保使用登录本系统的微信账号扫码 -->
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="RechargeVisible = false">取消</el-button>
            <el-button type="primary" @click="RechargeVisible = false"
              >确认</el-button
            >
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import reportPagination from '../../components/reportPagination.vue'
import { ref, reactive, watch, onMounted, computed } from 'vue'
const dialogFormVisible = ref(false)
const dialogTableVisible = ref(false)
import { order } from '../../api/order'
import { wallet } from '../../api/wallet';
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useRouter } from 'vue-router'
const router = useRouter()
const handleNameClick = (row) => {
  if (row.price === '0') {
    // 解析免费报告详情页的完整URL
    const freeUrl = router.resolve({
      name: 'productDetail',
      params: { code: row.report_code }
    }).href;

    // 在新标签页打开免费报告
    window.open(freeUrl, '_blank');
  } else {
    // 解析付费报告详情页的完整URL
    const paidUrl = router.resolve({
      name: 'productDetailcharge',
      params: { code: row.report_code }
    }).href;

    // 在新标签页打开付费报告
    window.open(paidUrl, '_blank');
  }
}

// 日期格式
const formatTime = ts => dayjs.unix(typeof ts === 'string' ? Number(ts) : ts).format('YYYY-MM-DD HH:mm')
// 提现状态标签类型
const getWithdrawStatusType = (status) => {
  const numStatus = Number(status)
  return numStatus === 3 ? 'success'    // 打款完成
    : numStatus === 2 ? 'warning'      // 打款中
      : numStatus === 1 ? 'warning'      // 等待打款
        : numStatus === 0 ? 'primary'      // 审核中
          : 'danger'                         // 已驳回
}

// 提现状态文本
const getWithdrawStatusText = (status) => {
  const numStatus = Number(status)
  return numStatus === 0 ? '审核中'
    : numStatus === 1 ? '等待打款'
      : numStatus === 2 ? '等待收款'
        : numStatus === 3 ? '打款完成'
          : numStatus === -1 ? '已驳回'
            : '未知状态'
}
const props = defineProps({
  wallets: {
    type: Array,
    default: () => [],
    required: true
  },
  balances: {
    type: Object,
    default: () => ({}),
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  total: { type: Number, default: 0 },
  initialPage: { type: Number, default: 1 },
  initialSize: { type: Number, default: 10 },
})
const emit = defineEmits(['myAccDetail'])
// 分页
const currentPage = ref(props.initialPage)
const pageSize = ref(props.initialSize)
watch(() => props.initialPage, v => currentPage.value = v)
watch(() => props.initialSize, v => pageSize.value = v)


watch(() => props.uploadsdata, v => reportList.value = v)


const handleCurrentChange = (page) => {
  currentPage.value = page
  emit('myAccDetail', { pageNum: page, pageSize: pageSize.value })
}
const handleSizeChange = (limit) => {
  pageSize.value = limit
  currentPage.value = 1
  emit('myAccDetail', { pageNum: 1, pageSize: limit })
}
// 个人认证表单
const personDialogVisible = ref(false)
const personForm = reactive({
  realName: '',
  cardNo: '',
  email: ''
})
const authentication = ref(false)
const addNewPerson = () => {

  personDialogVisible.value = true
}


const form = reactive({

  realName: '',
  cardNo: '',
  amount: '', // 包含多个订单的总金额
  email: ''
})

// 订单数据
const orders = ref(props.wallets)
// 钱包余额
const balance = ref(props.balances)
// 添加数据监听
watch(() => props.wallets, (newVal) => {
  orders.value = newVal
})
watch(() => props.balances, (newVal) => {
  balance.value = newVal
})




// 状态标签类型
// 在 script 中添加方法
const getStatusType = (status) => {
  const numStatus = Number(status)
  return numStatus === 3 ? 'success'
    : numStatus === 2 ? 'primary'
      : numStatus === 1 ? 'warning'
        : 'danger'
}

const getStatusText = (status) => {
  const numStatus = Number(status)
  return numStatus === 1 ? '待结算'
    : numStatus === 2 ? '正在结算'
      : numStatus === 3 ? '结算完成'
        : '结算出错'
}

const gridData = ref([])
const personMsg = ref(false)

// 提现弹窗
const withdraw = async () => {
  dialogFormVisible.value = true;
  const res = await order.GetUserInfo();
  if (res.code === 0 && res.data.certPerson) {
    const status = Number(res.data.certPerson.checkStatus);
    if (status === 1) {
      personMsg.value = true;
      Object.assign(form, {
        realName: res.data.certPerson.realName,
        cardNo: res.data.certPerson.cardNo,
        email: res.data.certPerson.email,
      });
    } else {
      personMsg.value = false;
    }
  }
};



// 立即收款
const handleReceive = (row) => {
  dialogCodeVisible.value = true

  imgcode.value = row.imgUrl

}
const Rechargeimgcode = ref('')
const RechargeVisible = ref(false)
const RechargeTxt = ref('')

// 充值记录查看详情
const showDetail = (row) => {
  RechargeVisible.value = true
  Rechargeimgcode.value = row.imgUrl

  const status = Number(row.payStatus)
  if (status == 1) {
    // 支付成功
    RechargeTxt.value = '充值成功！请使用微信扫描二维码查看充值详情。'
  }
  else if (status == 0) {
    // 待支付
    RechargeTxt.value = '充值待支付，请使用微信扫描二维码完成支付。'
  }
  else if (status == -1) {
    // 支付失败
    RechargeTxt.value = '充值失败，请使用微信扫描二维码查看详情，或联系客服。'
  }
  else {
    // 其他状态
    RechargeTxt.value = '请使用微信扫描二维码查看充值详情。'
  }
}


const dialogCodeVisible = ref(false)
const imgcode = ref('')
const ConfirmWithdrawal = async () => {
  try {
    // // 如果未认证，先提交个人信息
    // if (!personMsg.value) {
    //   const infoRes = await order.GetUserInfo(form)
    //   if (infoRes.code !== 0) {
    //     throw new Error(infoRes.msg || '认证失败')
    //   }
    // }
    // 进行提现
    const wRes = await wallet.withdraw({ amount: form.amount })
    if (wRes.code === 0) {
      imgcode.value = wRes.data.cashMoney.imgUrl
      dialogCodeVisible.value = true
      // ElMessage.success(wRes.data.cashMoney.txt)
      dialogFormVisible.value = false
      form.amount = ''
      emit('myAccDetail')
    } else {
      throw new Error(wRes.msg)
    }
  } catch (err) {
    ElMessage.error(err.message)
  }
}


const walletQuery = reactive({
  pgeNum: 1,
  pageSize: 5,
  total: 0
})
const handleCurrentChangewallet = (page) => {
  walletQuery.pageNum = page
  Withdrawal()
}
const handleSizeChangewallet = (limit) => {
  walletQuery.pageSize = limit;
  walletQuery.pageNum = 1;  // 重置到第一页
  Withdrawal()
}
const Withdrawal = async () => {
  const res = await wallet.getWithdrawRecord(walletQuery)
  if (res.code === 0) {
    gridData.value = res.data.cashList.info
    walletQuery.total = res.data.cashList.num
  }

  dialogTableVisible.value = true
}


const FlowingWaterVisible = ref(false)
const FlowingWaterData = ref([])
const FlowingWaterParams = reactive({ pageNum: 1, pageSize: 5, total: 0 })
const handleCurrentChangeFlowingWater = (page) => {
  FlowingWaterParams.pageNum = page
  FlowingWater()
}
const handleSizeChangFlowingWater = (limit) => {
  FlowingWaterParams.pageSize = limit;
  FlowingWaterParams.pageNum = 1;  // 重置到第一页
  FlowingWater()
}

// 资金流水
const FlowingWater = async () => {
  const res = await wallet.getFlow(FlowingWaterParams)
  FlowingWaterVisible.value = true
  FlowingWaterData.value = res.data.accountList.info
  FlowingWaterParams.total = res.data.accountList.num
}



const dialogRechargeVisible = ref(false)
const RechargeData = ref([])
// 充值状态标签类型
const getRechargeStatusType = (status) => {
  const numStatus = Number(status);
  return numStatus === 1 ? 'success'    // 成功
    : numStatus === 0 ? 'warning'      // 待付款
      : 'danger';                      // 失败
}

// 充值状态文本
const getRechargeStatusText = (status) => {
  const numStatus = Number(status);
  return numStatus === 0 ? '待付款'
    : numStatus === 1 ? '成功'
      : numStatus === -1 ? '失败'
        : '未知状态';
}

// 充值记录分页参数
const rechargeQuery = reactive({
  pageNum: 1,
  pageSize: 5
})
const rechargeTotal = ref(0)

// 分页事件处理
const handleCurrentChangeRecharge = (page) => {
  rechargeQuery.pageNum = page;
  Rechargerecord();
}
const handleSizeChangeRecharge = (limit) => {
  rechargeQuery.pageSize = limit;
  rechargeQuery.pageNum = 1;
  Rechargerecord();
}

// 修改充值记录获取方法
const Rechargerecord = async () => {
  const res = await wallet.getRecharge(rechargeQuery);
  if (res.code === 0) {
    RechargeData.value = res.data.cashList.info;
    rechargeTotal.value = res.data.cashList.num;
  }
  dialogRechargeVisible.value = true;
}

</script>

<style lang="scss" scoped>
.content-section {
  animation: fadeIn 0.3s ease;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wallet-balance {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wallet-balance-card {
  display: flex;
  height: 220px;
  padding: 20px;
  border-radius: 8px;

  .wallet-balance-btn {
    width: 200px;
    height: 200px;
    display: flex;
    align-items: end;
    margin-left: 10px;
  }

  .wallet-balance-img {
    background: url("../../assets/xwimg/wallet.png") center/cover no-repeat;
    margin: 0 auto;
    width: 500px;
    height: 200px;
    display: flex;
    flex-direction: column;

    justify-content: center;
    .balance-info {
      margin-left: 20px;

      display: flex;
      flex-direction: column;
      font-size: 24px;
      font-weight: bold;
      color: #409eff;
      .balance-text {
        font-size: 16px;
        color: #606266;
      }

      .balance-amount {
        margin-top: 10px;
        font-size: 60px;
        font-weight: 600;
      }
    }

    .balance-detail {
      margin-top: 10px;
      margin-left: 20px;
      display: flex;
      font-size: 14px;
      .detail-label {
        color: #606266;
      }

      .detail-amount {
        font-weight: bold;
        color: #409eff;
      }
    }
  }
}
.dialog-footer {
  text-align: right;
  padding: 10px 20px;
}
.name-link {
  display: inline-block;
  max-width: 300px; /* 根据你想要的宽度调整 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #409eff; /* Element Plus 主色，也可按需调整 */
  cursor: pointer;
  text-decoration: none; /* 去掉下划线 */
}
.name-link:hover {
  text-decoration: underline;
}
modify-tip {
  margin: 20px 0;
  text-align: center;
  font-size: 14px;
  color: #606266;
}
.auth-link {
  color: #409eff;
  text-decoration: underline;
  cursor: pointer;
}
.auth-link:hover {
  color: #66b1ff;
}
.qrcode-container {
  text-align: center;
  padding: 10px 0;

  .qrcode-text {
    font-size: 16px;
    color: #606266;
    margin-bottom: 20px;
  }

  .qrcode-image-wrapper {
    padding: 15px;
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    display: inline-block;
    margin: 10px auto;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    img {
      width: 200px;
      height: 200px;
      display: block;
    }
  }

  .qrcode-hint {
    font-size: 13px;
    color: #909399;
    margin-top: 15px;
  }
}
</style> 